'use strict'

const LIMIT = 20
const PAGE = 1

module.exports = async function(ctx, next) {
    if (!ctx.state.pagination) {
        const limit = Math.min(1000, parseInt(ctx.query.limit || LIMIT, 10))

        let offset
        let after
        let before

        if (ctx.query.after) {
            after = ctx.query.after
        } else if (ctx.query.before) {
            before = ctx.query.before
        } else if (ctx.query.offset) {
            offset = parseInt(ctx.query.offset, 10) || 0
        } else if (ctx.query.page) {
            const page = Math.max(1, parseInt(ctx.query.page || PAGE, 10))
            offset = limit * (page - 1)
        } else {
            offset = 0
        }

        ctx.state.pagination = {
            before,
            after,
            limit,
            offset
        }
    }

    await next()
}